package com.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author hjj
 * @create 2019-11-24 18:08
 */
public class NIOClient {
    private final static int PORT = 8889;
    private final static int BUFFER_SIZE = 1024;
    private final static String IP_ADDRESS = "127.0.0.1";

    private static void clientRq() {
        // 创建连接地址
        InetSocketAddress inetSocketAddress = new InetSocketAddress(IP_ADDRESS, PORT);
        // 声明一个连接通道
        SocketChannel socketChannel = null;
        // 创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
        try {
            // 打开通道
            socketChannel = SocketChannel.open();
            // 连接服务器
            socketChannel.connect(inetSocketAddress);
            while (true) {
                byte[] bytes = new byte[BUFFER_SIZE];
                System.in.read(bytes);
                byteBuffer.put(bytes);
                byteBuffer.flip();
                socketChannel.write(byteBuffer);
                System.out.println("NIO client send: " + new String(bytes));
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        clientRq();
    }
}
